package com.wxb.hello.auth.handler;

import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;

/**
 * CSRF匹配器
 * 配置需要排除CSRF拦截的uri
 *
 * @author Feng Yu
 * @version V1.0
 * @date 2017-06-15
 * @see org.springframework.security.web.csrf.CsrfFilter.DefaultRequiresCsrfMatcher
 */
public class CustRequiresCsrfMatcher implements RequestMatcher {

    private static final String excludeUrl = "/login,/api/alipay/back,/api/alipay/notify";
    private final HashSet<String> allowedMethods;

    public CustRequiresCsrfMatcher() {
        this.allowedMethods = new HashSet(Arrays.asList(new String[]{"GET", "HEAD", "TRACE", "OPTIONS"}));
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        String[] urlArr = StringUtils.commaDelimitedListToStringArray(excludeUrl);
        if (urlArr != null && urlArr.length > 0) {
            for (String url : urlArr) {
                String servletPath = request.getServletPath();
                if (servletPath.contains(url)) {
                    return false;
                }
            }
        }
        return !this.allowedMethods.contains(request.getMethod());
    }

}
